package studio.raptor.databus.dashboard.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import studio.raptor.databus.dashboard.common.DispatcherNode;
import studio.raptor.databus.dashboard.properties.TaskConfig;
import studio.raptor.databus.dashboard.repository.ZKRepository;
import studio.raptor.databus.dashboard.service.interfaces.TaskService;

/**
 * @author jack
 * @since 1.0
 */
@Service
public class TaskServiceImpl implements TaskService {

  private static final Logger log = LoggerFactory.getLogger(TaskServiceImpl.class);

  @Autowired
  ZKRepository zkRepository;

  @Override
  public String createDispatcher(String ip, Integer port, String name) {
    String instanse = ip + "-" + port;
    String serverPath = String.format(DispatcherNode.SERVER_NODE, instanse);
    log.debug("the dispatcher server ip:{},port:", ip, port);
    zkRepository.persist(serverPath, name);
    return instanse;
  }


  @Override
  public TaskConfig createDispatcherTask(TaskConfig taskProperties) {
    String serverNode = taskProperties.getIp() + "-" + taskProperties.getPort();
    String taskNode = taskProperties.getKindId() + "-" + taskProperties.getCode();
    String serverPath = String.format(DispatcherNode.SERVER_TASK_NODE, serverNode
        , taskNode);
    zkRepository.persist(serverPath, taskProperties.getStatus());
    return taskProperties;
  }

  @Override
  public String removeDispatcher(String ip, Integer port) {
    String instanse = ip + "-" + port;
    String serverPath = String.format(DispatcherNode.SERVER_NODE, instanse);
    log.debug("the dispatcher server ip:{},port:", ip, port);
    zkRepository.remove(serverPath);
    return instanse;
  }

  @Override
  public TaskConfig updateDispatcherTask(TaskConfig taskProperties) {
    String serverNode = taskProperties.getIp() + "-" + taskProperties.getPort();
    String taskNode = taskProperties.getKindId() + "-" + taskProperties.getCode();
    String serverPath = String.format(DispatcherNode.SERVER_TASK_NODE, serverNode
        , taskNode);
    zkRepository.update(serverPath, taskProperties.getStatus());
    return taskProperties;
  }

}
